﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RestSharp;
using Newtonsoft.Json.Linq;

namespace Tradier
{
    public partial class CancelOrder : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var accessToken = Session["UserTradierAccessToken"];
            if (accessToken == null)
            {
                Response.Redirect("/login.aspx");
            }

            string orderId = Request.QueryString["id"];
            string accountId = Request.QueryString["account_id"];

            if (string.IsNullOrEmpty(orderId) || string.IsNullOrEmpty(accountId))
            {
                Response.Redirect("/UserOrders.aspx");
            }

            CancelAccountOrder((string)accessToken, orderId, accountId);
        }

        private void CancelAccountOrder(string token, string orderId, string accountId)
        {
            try
            {
                var client = new RestClient("https://api.tradier.com");

                string requestStr = String.Format("/v1/accounts/{0}/orders/{1}", accountId, orderId);
                var request = new RestRequest(requestStr, Method.DELETE);
                request.AddHeader("Authorization", "Bearer " + token);

                var result = (client.Execute(request).Content);
                var json = JObject.Parse(result);

                var status = json["order"]["status"];
                if (status.Equals("ok"))
                {

                }
            }
            catch
            {
            }
            finally
            {
                Response.Redirect("/UserOrders.aspx");
            }
        }
    }
}